<template>
    <div class="wrapper">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <!-- 提示框 -->
            <el-alert
                title="添加商品信息"
                type="info"
                center
                show-icon>
            </el-alert>


            <!-- 步骤条 -->
            <el-steps :active="active" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form :model="fromData" :rules="fromDataRules" ref="fromDataRef">
                <el-tabs tab-position="left" v-model="activeName" @tab-click="handleClick" :before-leave='switch_label'>
                    <!-- 基本信息 -->
                    <el-tab-pane label="基本信息" name="1">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="fromData.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格(元)" prop="goods_price">
                            <el-input v-model="fromData.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量(kg)" prop="goods_weight">
                            <el-input v-model="fromData.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量(个)" prop="goods_number">
                            <el-input  v-model="fromData.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <br>
                            <el-cascader
                                v-model="fromData.goods_cat"
                                :options="commodity_categories"
                                :props="{ expandTrigger: 'hover', label: 'cat_name', value: 'cat_id', children: 'children' }"
                                @change="handleChange">
                            </el-cascader>
                        </el-form-item>
                    </el-tab-pane>

                    <!-- 商品参数 -->
                    <el-tab-pane label="商品参数" name="2">
                        <el-row v-for="val in commodity_params" :key='val.attr_id'>
                            {{val.attr_name}}
                            <el-checkbox-group v-model="val.attr_vals">
                                <el-checkbox border v-for="(item, i) in val.attr_vals" :label="item" :key='i'></el-checkbox>
                            </el-checkbox-group>
                        </el-row>
                    </el-tab-pane>

                    <!-- 商品属性 -->
                    <el-tab-pane label="商品属性" name="3">
                        <el-row v-for="(val) in commodity_attribute" :key="val.attr_id">
                            {{val.attr_name}}
                            <el-input v-model="val.attr_vals"></el-input>
                        </el-row>
                    </el-tab-pane>

                    <!-- 商品图片 -->
                    <el-tab-pane label="商品图片" name="4">
                        <el-upload
                            class="upload-demo"
                            :action="actionPath"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            list-type="picture"
                            :headers="headersObj"
                            :on-success="successFun">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>

                    <!-- 商品内容 -->
                    <el-tab-pane label="商品内容" name="5">
                        <quill-editor v-model="fromData.goods_introduce"></quill-editor>
                        <el-button class="btn" type="primary" @click="add_commodity_submit">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>

            <!-- 预览图片 -->
            <el-dialog
                title="图片预览"
                :visible.sync="priview_dialogVisible"
                width="50%">
                <img :src="preViewPath" class="img">
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: 'Add',
        data() {
            return {
                active: 0,
                activeName: "1",
                commodity_categories: [],
                selectValue: [],
                fromData: {
                    goods_name: '',
                    goods_cat: '',
                    goods_price: 1,
                    goods_number: 1,
                    goods_weight: 1,
                    goods_introduce: '',
                    pics: [],
                    attrs: []
                },
                // 基本信息校验
                fromDataRules: {
                    goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                    goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
                    goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
                    goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
                    goods_weight: [{ required: true, message: '请输入商品重量',  trigger: 'blur' }]
                },
                // 商品参数列表(动态参数)
                commodity_params: '',
                // 商品属性列表(静态参数)
                commodity_attribute: '',
                // 上传图片地址
                actionPath: '/up/upload',
                // 设置upload请求头
                headersObj: {
                    Authorization: window.sessionStorage.getItem('token')
                },
                // 预览图片地址
                preViewPath: '',
                // 预览对话框状态
                priview_dialogVisible: false
            }
        },
        created() {
            this.get_commodity_categories();
        },
        methods: {
            // 获取商品分类列表
            async get_commodity_categories() {
                const {data: res} = await this.$http.get('/categories');
                if(res.meta.status !== 200) return this.$message.error('获取商品列表失败');
                this.commodity_categories = res.data;
            },
            
            // 监听步骤条的切换
            handleClick() {
                this.active = this.activeName*1-1;
            },

            // 获取商品参数(动态)
            async get_commodity_params_active(goods_cat) {
                const {data: active} = await this.$http.get(`categories/${goods_cat[2]}/attributes`, {
                    params: {
                        sel: 'many'
                    }
                })
                if(active.meta.status !== 200) return this.$message.error('获取商品参数失败')
                active.data.forEach((value, index) => {
                    if(value.attr_vals === '') {
                        active.data[index].attr_vals = []
                    }else {
                        active.data[index].attr_vals = value.attr_vals.split(',');
                    }
                })
                this.commodity_params = active.data;
            },
            
            // 获取商品参数(静态)
            async get_commodity_params_static(goods_cat) {
                const {data: res} = await this.$http.get(`categories/${goods_cat[2]}/attributes`, {
                    params: {
                        sel: 'only'
                    }
                });
                if(res.meta.status !== 200) return this.$message.error('商品属性获取失败');
                this.commodity_attribute = res.data;
                // console.log(this.commodity_attribute);
            },

            // 级联选择器发生改变的时候触发该方法
            handleChange() {
                if(this.fromData.goods_cat.length !== 3) {
                    this.$message.info('请选择三级列表')
                    this.fromData.goods_cat = [];
                    return
                }
                
                // 获取商品参数(动态参数)
                this.get_commodity_params_active(this.fromData.goods_cat);
                // 获取商品属性(静态参数)
                this.get_commodity_params_static(this.fromData.goods_cat)

                // 调整参数
                this.fromData.goods_cat = this.fromData.goods_cat.join()
            },
            // Tab标签页切换之前的钩子
            switch_label(activeName, oldActiveName) {
                let key = '';
                if(oldActiveName === "1") {
                    this.$refs.fromDataRef.validate(valid => {
                        if(!valid) {
                            this.$message.info('请完善基本信息')
                            key = valid;
                        }
                    })
                }
                return key;
            },
            
            // 预览图片
            handlePreview(file) {
                this.preViewPath = file.response.data.url;
                this.priview_dialogVisible = true;

            },
            // 删除图片
            handleRemove(file) {
                let fileName = file.response.data.tmp_path;
                const index = this.fromData.pics.findIndex(val => {
                    val.pic === fileName;
                })
                this.fromData.pics.splice(index, 1);
            },
            // 上传图片成功钩子
            successFun(res) {
                this.fromData.pics.push({
                    pci: res.data.tmp_path
                })
            },

            // 提交
            async add_commodity_submit() {
                // console.log(this.commodity_params);
                // console.log(this.commodity_attribute)
                // 处理动态参数
                this.commodity_params.forEach(item => {
                    const newInfo = {
                        "attr_id": item.attr_id,
                        "attr_value": item.attr_vals.join(',')
                    }
                    this.fromData.attrs.push(newInfo);
                })

                // 处理静态属性
                this.commodity_attribute.forEach(item => {
                    const newInfo = {
                        "attr_id": item.attr_id,
                        "attr_value": item.attr_vals
                    }
                    this.fromData.attrs.push(newInfo);
                })
                const {data: res} = await this.$http.post('/goods', this.fromData);
                if(res.meta.status !== 201) {
                    this.fromData.attrs = [];
                    this.$message.error('添加商品失败')
                    return
                }
                this.$message.success('添加商品成功');
                this.$router.push({name: 'goods'});
            }
        },
        watch: {
            // commodity_params: {
            //     deep: true,
            //     handler(newValue) {
            //         console.log(newValue);
            //     }
            // },
            // commodity_attribute: {
            //     deep: true,
            //     handler(newValue) {
            //         console.log(newValue);
            //     }
            // }
        }
    }
</script>

<style  lang="less" scoped>
    .wrapper{
        width: 100%;
        height: 0px;
        padding: 10px 20px;
        box-sizing: border-box;
        .el-steps{
            padding: 20px;
        }
        .el-tab-pane{
            font-size: 13px;
            .el-input{
                margin-top: 10px;
                font-size: 13px;
            }
        }
        .el-row{
            margin: 20px;
        }
        .el-checkbox-group{
            margin-top: 10px;
        }
        .el-checkbox{
            margin: 0 10px 0 0!important;
        }
        .img{
            width: 100%;
        }
        .btn{
            margin-top: 20px;
        }
    }
</style>